﻿using System;
using System.Linq;
using System.Web.Mvc;
using AttributeRouting;
using AttributeRouting.Web.Mvc;
using PH.Model.Achievements;
using PH.Logic.Achievements;
using PH.Logic.Schools;
namespace PH.Web.Management.Areas.Achievements.Controllers
{
    [RouteArea("Achievements")]
    [RoutePrefix("Mark")]
    [Authorize]
    public class MarkController : Controller
    {
        /// <summary>
        /// 过期的
        /// </summary>
        /// <returns></returns>
        [Route("")]
        [Filters.CurrentSchool]
        public ActionResult Index()
        {
            return View();
        }

        [Route("InputMarks")]
        [Filters.CurrentSchool]
        public ActionResult InputMarks()
        {
            return View();
        }
        
        [Route("Result")]
        [Filters.CurrentSchool]
        public ActionResult Result()
        {
            return View();
        }

        [Route("Edit/{id:int}")]
        [Filters.CurrentSchool]
        public ActionResult Edit(int id)
        {
            var model = MarkLogic.GetModel(id);
            return PartialView(model);
        }

        [Route("Export")]
        [Filters.CurrentSchool]
        public ActionResult Export()
        {
            try
            {
                if (!string.IsNullOrEmpty(Request.Form.Get("archiveGuid")))
                {
                    
                    
                    var query=new PH.Model.Analyses.Schools.S4StudentQuery();
                    query.ArchiveGuid = new Guid(Request.Form.Get("archiveGuid"));
                    query.SchoolGuid = PH.Web.Global.WebContext.CurrentSchool.Guid;
                    var rets = PH.Logic.Analyses.SchoolLogic.GetS4Student(query);
                    if (rets.TotalRecordsCount > 0)
                    {
                        Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();
                        workbook.Open(Server.MapPath("/RootFiles/Templates/mark_export.xls"));

                        #region 总分列表
                        var sheet = workbook.Worksheets[0];
                        var cells = sheet.Cells;
                        for (var i=0;i<rets.TotalRecordsCount;i++)
                        {
                            var item = rets[i];
                            cells[i + 1, 0].PutValue(item.StudentNo);
                            cells[i + 1, 1].PutValue(item.ClassName);
                            cells[i + 1, 2].PutValue(item.RealName);
                            cells[i + 1, 3].PutValue(item.Sex == 1 ? "男" : "女");
                            cells[i + 1, 4].PutValue(item.StandardScore);
                            cells[i + 1, 5].PutValue(item.AdditionalScore);
                            cells[i + 1, 6].PutValue(item.TotalScore);
                            cells[i + 1, 7].PutValue(PH.Model.Help.GetScoreLevel(item.ScoreLevel));
                        }
                        #endregion

                        #region 分项目成绩
                        MarkQuery sea = new MarkQuery();
                        if (!string.IsNullOrEmpty(Request.Form.Get("classID")))
                            sea.ClassID = int.Parse(Request.Form.Get("classID"));
                        sea.SchoolGuid = PH.Web.Global.WebContext.CurrentSchool.Guid;
                        if (!string.IsNullOrEmpty(Request.Form.Get("archiveGuid")))
                            sea.ArchiveGuid = new Guid(Request.Form.Get("archiveGuid"));
                        if (!string.IsNullOrEmpty(Request.Form.Get("SubjectID")))
                            sea.SubjectID = int.Parse(Request.Form.Get("subjectID"));
                        if (!string.IsNullOrEmpty(Request.Form.Get("sex")))
                            sea.Sex = byte.Parse(Request.Form.Get("sex"));
                        sea.Key = Request.Form.Get("key");
                        sea.GetStudentName = true;
                        var lst = MarkLogic.Gets(sea);
                        if (lst.Count > 0)
                        {
                            var sids = lst.Select(p => p.SubjectID).Distinct();
                            var subjects = Logic.Standards.SubjectLogic.GetSubjects(null);
                            foreach (var sid in sids)
                            {
                                var sub = subjects.Find(p => p.ID == sid);
                                workbook.Worksheets.AddCopy(1);
                                var sc = workbook.Worksheets.Count;
                                sheet = workbook.Worksheets[sc - 1];
                                sheet.Name = sub.SubjectName;
                                cells = sheet.Cells;
                                var marks = lst.FindAll(p => p.SubjectID == sid);
                                for (var i = 0; i < marks.Count; i++)
                                {
                                    var item = marks[i];
                                    cells[i + 1, 0].PutValue(item.StudentNo);
                                    cells[i + 1, 1].PutValue(item.ClassName);
                                    cells[i + 1, 2].PutValue(item.StudentName);
                                    cells[i + 1, 3].PutValue(item.Sex == 1 ? "男" : "女");
                                    cells[i + 1, 4].PutValue(item.Achievement);
                                    cells[i + 1, 5].PutValue(item.Score);
                                    cells[i + 1, 6].PutValue(item.Description);
                                }
                            }
                            workbook.Worksheets.RemoveAt(1);
                            var buffer = workbook.SaveToStream().ToArray();
                            return File(buffer, "application/octet-stream", "成绩明细.xls");
                        }
                        #endregion
                    }
                }
                return Content("暂无数据");
                
            }
            catch (Exception ex)
            {
                Common.Logger.Error("", ex);
                return Content("服务器运行出错，请联系开发商。");
            }
        }

        [Route("List")]
        public ActionResult List()
        {
            return View();
        }

        [Route("AnalysisInSchool")]
        [Filters.CurrentSchool]
        public ActionResult AnalysisInSchool()
        {
            return View();
        }

        [Route("DownTemplate/{grade:int}")]
        [Filters.CurrentSchool]
        public ActionResult DownTemplate(int grade)
        {
            try
            {
                var students = Logic.Schools.StudentLogic.GetStudents(new Model.Schools.StudentQuery()
                {
                    SchoolGuid = Global.WebContext.CurrentSchool.Guid,
                    GradeCode=grade
                });
                if (students != null && students.TotalRecordsCount > 0)
                {
                    Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();
                    workbook.Open(Server.MapPath(string.Format("/RootFiles/Templates/mark_{0}.xls", grade < 21 ? 1 : 2)));
                    var sheet = workbook.Worksheets[0];
                    var cells = sheet.Cells;
                    for (var i = 0; i < students.TotalRecordsCount;i++)
                    {
                        var stu = students[i];
                        cells[i + 1, 0].PutValue(stu.StudentNo);
                        cells[i + 1, 3].PutValue(stu.GradeCode);
                        cells[i + 1, 4].PutValue(string.Format("{0}{1:00}", stu.GradeCode, stu.ClassIndex));
                        cells[i + 1, 5].PutValue(stu.ClassName);
                        cells[i + 1, 6].PutValue(stu.StudentNumber);
                        cells[i + 1, 7].PutValue(stu.NationID);
                        cells[i + 1, 8].PutValue(stu.RealName);
                        cells[i + 1, 9].PutValue(stu.Sex);
                        cells[i + 1, 10].PutValue(stu.Birthday);
                        cells[i + 1, 11].PutValue(stu.Address);
                    }
                    var buffer = workbook.SaveToStream().ToArray();
                    return File(buffer, "application/octet-stream", "成绩模板.xls");
                }
                else
                    return Content("暂无数据");
            } 
            catch (Exception ex)
            {
                Common.Logger.Error("", ex);
                return Content("服务器运行出错，请联系开发商。");
            }
        }

        [Route("ChangeMark")]
        [Filters.CurrentSchool]
        public ActionResult ChangeMark()
        {
            return View();
        }

        [Route("DetailByStudent/{studentGuid:guid}")]
        public ActionResult DetailByStudent(Guid studentGuid)
        {
            var stu = StudentLogic.GetStudent(studentGuid);
            return PartialView(stu);
        }

        [Route("StudentList")]
        [Filters.CurrentSchool]
        public ActionResult StudentList()
        {
            return View();
        }
    }
}
